package com.qianfeng.openplatform.geteway.fiter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openplatform.commons.field.ResponseMessage;
import com.qianfeng.openplatform.commons.field.StaticField;
import com.qianfeng.openplatform.geteway.client.CacheClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 江江
 * @Date 2020/7/29 19:11
 * 单点登录 2020/7/29/19:11 http://localhost:42000/login?userName=admin&password=admin
 * http://www.openapi.sys/openapi?method=loginserver&userName=admin&appkey=msmsms23330&password=admin
 */
@Component
public class JwtFilter extends ZuulFilter {
    @Autowired
    private CacheClient cacheClient;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //不要拦截登录请求
        String method = request.getParameter("method");
        if ("loginserver".equals(method)){
            return null;
        }

       // String jwt = request.getHeader("compace_token");

        try {
            String appkey = request.getParameter("appkey");
            String jwt = cacheClient.getFromRedis("compace_token"+appkey);

            Jws<Claims> jws = Jwts.parser().setSigningKey("shayebuzhidao").parseClaimsJws(jwt);
            Claims body = jws.getBody();
            return null;
        } catch (Exception e) {
            requestContext.setSendZuulResponse(false);
            ObjectMapper objectMapper = new ObjectMapper();
            HttpServletResponse response = requestContext.getResponse();
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().write(objectMapper.writeValueAsString(new ResponseMessage(StaticField.REQEST_LOGON_ERROR_CODE, "没有登录....赶紧去去登录")));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

        return null;
    }
}
